<script setup lang="ts">
import { onMounted, onUnmounted, ref, computed, watch, nextTick } from "vue";
import { ElInput, ElButton } from "element-plus";
import axios from "axios";
import { Icon } from 'vant';
import { useRouter, useRoute } from 'vue-router';
import { getCurrentUser } from '@/utils/userStore';
import { getMembershipCard, getCurrentMemberLevel } from '@/utils/membershipStore';

// 导入国际化语言包（与个人页面保持一致）
const i18n = {
  zh: {
    viaEyeMovement: "搜索视频内容...",
    videoShareZone: "视频分享专区",
    all: "全部",
    running: "跑步",
    cycling: "骑行",
    yoga: "瑜伽",
    fitness: "健身",
    justReleased: "刚刚发布",
    daysAgo: "天前",
    hoursAgo: "小时前",
    minutesAgo: "分钟前",
    today: "今日",
    aiAssistant: "AI助手",
    aiFitnessAssistant: "AI健身助手",
    enterYourQuestion: "请输入你的问题...",
    customerService: "客服中心"
  },
  en: {
    viaEyeMovement: "Search video content...",
    videoShareZone: "Video Sharing Zone",
    all: "All",
    running: "Running",
    cycling: "Cycling",
    yoga: "Yoga",
    fitness: "Fitness",
    justReleased: "Just released",
    daysAgo: "days ago",
    hoursAgo: "hours ago",
    minutesAgo: "minutes ago",
    today: "Today",
    aiAssistant: "AI Assistant",
    aiFitnessAssistant: "AI Fitness Assistant",
    enterYourQuestion: "Please enter your question...",
    customerService: "Customer Service"
  },
  jp: {
    viaEyeMovement: "動画コンテンツを検索...",
    videoShareZone: "動画共有ゾーン",
    all: "すべて",
    running: "ランニング",
    cycling: "サイクリング",
    yoga: "ヨガ",
    fitness: "フィットネス",
    justReleased: "新しく公開",
    daysAgo: "日前",
    hoursAgo: "時間前",
    minutesAgo: "分前",
    today: "今日",
    aiAssistant: "AIアシスタント",
    aiFitnessAssistant: "AIフィットネスアシスタント",
    enterYourQuestion: "質問を入力してください...",
    customerService: "カスタマーサービス"
  }
};

// 明确声明 data 的类型
interface Item {
  id: number;
  name: string;
  img: string;
  state: number; // 0: 未点赞, 1: 已点赞
  type?: string;
  isVisible?: boolean;
  time?: string;
  isMemberOnly?: boolean; // 新增：是否为会员专属
  requiredLevel?: number; // 新增：需要的会员等级
}

// 聊天消息类型
interface ChatMessage {
  id: string;
  content: string;
  isUser: boolean;
  timestamp: Date;
}

const router = useRouter();
const route = useRoute();
const active = ref(0);
const searchKey = ref("");
const isSearched = ref(false);
const data = ref<Item[]>([]);
const currentType = ref("all"); // 使用英文键名便于国际化映射

// 语言状态管理 - 从本地存储读取初始值
const currentLang = ref(localStorage.getItem('appLang') || 'zh');

// 会员相关状态
const showMembershipPopup = ref(false);
const currentUser = ref<any>(null);
const userMembership = ref<any>(null);
const currentMemberLevel = ref<any>(null);
const selectedVideo = ref<Item | null>(null);

// AI聊天相关状态
const showAIChat = ref(false);
const chatMessages = ref<ChatMessage[]>([]);
const currentMessage = ref("");
const isLoading = ref(false);
const chatContainer = ref<HTMLElement>();

// 运动类型映射（用于国际化显示）
const sportTypes = {
  all: { zh: "全部", en: "All", jp: "すべて" },
  running: { zh: "跑步", en: "Running", jp: "ランニング" },
  cycling: { zh: "骑行", en: "Cycling", jp: "サイクリング" },
  yoga: { zh: "瑜伽", en: "Yoga", jp: "ヨガ" },
  fitness: { zh: "健身", en: "Fitness", jp: "フィットネス" }
};

// 获取当前语言的文本
const getText = (key: keyof typeof i18n.zh) => {
  return i18n[currentLang.value as keyof typeof i18n][key] || i18n.zh[key];
};

// 获取运动类型的当前语言文本
const getSportTypeText = (typeKey: string) => {
  // @ts-ignore - 简化处理类型映射
  return sportTypes[typeKey]?.[currentLang.value as keyof typeof sportTypes[keyof typeof sportTypes]] || typeKey;
};

const filteredData = computed(() => {
  return data.value.filter(item => {
    // 类型匹配（支持国际化类型名）
    const typeMatch = currentType.value === "all" ||
      item.type === getSportTypeText(currentType.value) ||
      item.type === sportTypes[currentType.value as keyof typeof sportTypes].zh;
    // 添加返回语句和闭合大括号
    return typeMatch;
  });
});

const categories = ["跑步", "骑行", "瑜伽", "健身"];

// 重命名为 filteredVideoData 以避免命名冲突
const filteredVideoData = computed(() => {
  // 先筛选
  let arr = data.value.filter(item => {
    if (currentType.value === "会员专属") {
      return item.isMemberOnly;
    }
    const typeMatch = currentType.value === "全部" || item.type === currentType.value;
    const searchMatch = !searchKey.value || !searchKey.value.trim() ||
      item.name.toLowerCase().includes(searchKey.value.toLowerCase());
    return typeMatch && searchMatch;
  });
  // 洗牌（打乱顺序）
  arr = arr.slice().sort(() => Math.random() - 0.5);
  return arr;
});

// 检查用户是否可以访问视频
const canAccessVideo = (video: Item) => {
  if (!video.isMemberOnly) return true;
  if (!currentMemberLevel.value) return false;
  return (currentMemberLevel.value.level || 0) >= (video.requiredLevel || 1);
};

// 获取会员等级名称


// 初始化用户和会员信息
const initUserAndMembership = () => {
  currentUser.value = getCurrentUser();
  userMembership.value = getMembershipCard();
  currentMemberLevel.value = getCurrentMemberLevel();
};

const getData = async () => {
  try {
    const response = await axios.get("http://localhost:3000/api/video-list");
    // 给每个item加上likes和state字段，初始为0
    data.value = response.data.map((item: any) => ({
      ...item,
      state: item.state ?? 0,
      isMemberOnly: item.isMemberOnly ?? false,
      requiredLevel: item.requiredLevel ?? 1
    }));
  } catch (error) {
    console.error('获取视频数据失败:', error);
  }
};

const goToDetail = (item: Item) => {
  // 只要是会员专属视频，点击都弹出会员弹窗
  if (item.isMemberOnly) {
    selectedVideo.value = item;
    showMembershipPopup.value = true;
    return;
  }
  router.push({
    name: 'LLQxq',
    params: { id: item.id },
    query: { tab: active.value }
  });
};

// 升级会员
const upgradeMembership = () => {
  showMembershipPopup.value = false;
  router.push('/my'); // 跳转到个人页面查看会员卡
};

// 关闭会员弹窗
const closeMembershipPopup = () => {
  showMembershipPopup.value = false;
  selectedVideo.value = null;
};

const goToSearchPage = () => {
  router.push({
    name: 'LLQss',
    query: { search: searchKey.value }
  });
};

const goToAIChat = () => {
  router.push({ name: 'LLQai' });
};

// AI聊天相关函数
const toggleAIChat = () => {
  showAIChat.value = !showAIChat.value;

  if (showAIChat.value && chatMessages.value.length === 0) {
    // 添加欢迎消息（根据当前语言）
    const welcomeMessages = {
      zh: "你好，我是健身助手，有什么可以帮你？",
      en: "Hello, I'm your fitness assistant. How can I help you?",
      jp: "こんにちは、フィットネスアシスタントです。何かお困りのことがありますか？"
    };

    chatMessages.value.push({
      id: '1',
      content: welcomeMessages[currentLang.value as keyof typeof welcomeMessages] || welcomeMessages.zh,
      isUser: false,
      timestamp: new Date()
    });
  }

  // 滚动到底部
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });
};

const sendMessage = async () => {
  if (!currentMessage.value.trim() || isLoading.value) return;

  const userMessage: ChatMessage = {
    id: Date.now().toString(),
    content: currentMessage.value,
    isUser: true,
    timestamp: new Date()
  };

  chatMessages.value.push(userMessage);
  const messageToSend = currentMessage.value;
  currentMessage.value = "";
  isLoading.value = true;

  // 滚动到底部
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });

  try {
    // 调用 Coze API
    const response = await fetch('https://api.coze.cn/open_api/v2/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer pat_yutogVv2KjpjRC9IOhyEoTRfnKlkcH7m2OO9f5t0eFa6W2payP7MublTyp7pQf3N',
      },
      body: JSON.stringify({
        bot_id: '7517883645723017251', // Coze机器人ID
        user: 'fitness_user', // 用户ID
        query: messageToSend, // 用户输入内容
        stream: false // 不使用流式
      })
    });

    const data = await response.json();

    // 解析 Coze 返回的内容
    let aiReply = data?.messages?.[0]?.content || getText('enterYourQuestion');

    // 尝试解析 content 是否为JSON对象
    try {
      const parsed = JSON.parse(aiReply);
      // 如果解析出来有 result/reply/text 字段，优先显示
      aiReply = parsed.result || parsed.reply || parsed.text || aiReply;
    } catch (e) {
      // 不是JSON则直接显示
    }

    const aiMessage: ChatMessage = {
      id: (Date.now() + 1).toString(),
      content: aiReply,
      isUser: false,
      timestamp: new Date()
    };

    chatMessages.value.push(aiMessage);
  } catch (err) {
    console.error('Coze API调用失败:', err);

    // 网络或API异常时的兜底回复（多语言）
    const fallbackReplies = {
      zh: [
        '您好！我是您的健身AI助手。我可以帮助您制定健身计划、解答运动问题、提供营养建议等。请告诉我您需要什么帮助？',
        '关于健身，我建议您：1. 制定合理的训练计划 2. 注意正确的动作姿势 3. 保持充足的休息 4. 均衡的饮食搭配。您想了解哪个方面？'
      ],
      en: [
        'Hello! I am your fitness AI assistant. I can help you create fitness plans, answer exercise questions, provide nutrition advice, etc. Please tell me how I can help you?',
        'Regarding fitness, I suggest you: 1. Create a reasonable training plan 2. Pay attention to correct movement posture 3. Maintain adequate rest 4. Have a balanced diet. Which aspect would you like to know about?'
      ],
      jp: [
        'こんにちは！フィットネスAIアシスタントです。トレーニング計画の作成、運動に関する質問の回答、栄養アドバイスなどを支援できます。どのようなご協力が必要ですか？',
        'フィットネスについてのアドバイス：1. 合理的なトレーニング計画を立てる 2. 正しい動作姿勢に注意する 3. 十分な休息を取る 4. バランスの良い食事を摂る。どの方面について詳しく知りたいですか？'
      ]
    };

    // 根据当前语言选择合适的兜底回复
    const langReplies = fallbackReplies[currentLang.value as keyof typeof fallbackReplies] || fallbackReplies.zh;
    const randomReply = langReplies[Math.floor(Math.random() * langReplies.length)];

    const fallbackMessage: ChatMessage = {
      id: (Date.now() + 1).toString(),
      content: `AI${getText('viaEyeMovement')}\n\n${randomReply}`,
      isUser: false,
      timestamp: new Date()
    };

    chatMessages.value.push(fallbackMessage);
  }

  isLoading.value = false;
  // 滚动到底部
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });
};

const closeAIChat = () => {
  showAIChat.value = false;
};

// AI图标点击处理
const handleAIClick = () => {
  toggleAIChat();
};

const onTabChange = (name: string) => {
  // 添加淡出动画
  const videoGrid = document.querySelector('.video-grid') as HTMLElement;
  if (videoGrid) {
    videoGrid.style.opacity = '0';
    videoGrid.style.transform = 'translateY(20px)';
  }

  // 延迟切换类型，让淡出动画完成
  setTimeout(() => {
    currentType.value = name;

    // 添加淡入动画
    setTimeout(() => {
      if (videoGrid) {
        videoGrid.style.opacity = '1';
        videoGrid.style.transform = 'translateY(0)';
      }
    }, 100);
  }, 200);
};

const onSearch = () => {
  isSearched.value = true;
};

const onImageLoad = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.classList.add('loaded');
};

function onImageError(event: Event) {
  const target = event.target as HTMLImageElement | null;
  if (target) {
    target.src = 'https://via.placeholder.com/120x90?text=No+Image';
  }
}

const initLazyLoading = () => {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target as HTMLImageElement;
        const dataSrc = img.getAttribute('data-src');
        if (dataSrc) {
          img.src = dataSrc;
          img.removeAttribute('data-src');
          observer.unobserve(img);
        }
      }
    });
  }, {
    rootMargin: '50px 0px',
    threshold: 0.1
  });

  const lazyImages = document.querySelectorAll('.lazy-image');
  lazyImages.forEach(img => {
    observer.observe(img);
  });
};

const formatTime = (timeStr: string) => {
  if (!timeStr) return getText('justReleased');
  const now = new Date();
  const time = new Date(timeStr);
  const diffMs = now.getTime() - time.getTime();
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  const diffMinutes = Math.floor(diffMs / (1000 * 60));

  if (diffDays > 0) {
    return `${diffDays}${getText('daysAgo')}`;
  } else if (diffHours > 0) {
    return `${diffHours}${getText('hoursAgo')}`;
  } else if (diffMinutes > 0) {
    return `${diffMinutes}${getText('minutesAgo')}`;
  } else {
    return getText('justReleased');
  }
};

// 监听本地存储的语言变化
const handleStorageChange = (e: StorageEvent) => {
  if (e.key === 'appLang' && e.newValue) {
    currentLang.value = e.newValue;
  }
};

onMounted(async () => {
  // 从本地存储获取当前语言
  currentLang.value = localStorage.getItem('appLang') || 'zh';
});


// 拖动AI图标相关逻辑
const aiIconPos = ref({ left: 0, top: 0 });
const aiIconDragging = ref(false);
const aiIconOffset = ref({ x: 0, y: 0 });
const aiIconRef = ref<HTMLElement | null>(null);

const onAiIconMouseDown = (e: MouseEvent) => {
  aiIconDragging.value = true;
  const icon = aiIconRef.value;
  if (icon) {
    const rect = icon.getBoundingClientRect();
    aiIconOffset.value = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    };
  }
  document.body.style.overflow = 'hidden'; // 禁止页面滚动
  document.addEventListener('mousemove', onAiIconMouseMove);
  document.addEventListener('mouseup', onAiIconMouseUp);
};
const onAiIconMouseMove = (e: MouseEvent) => {
  if (!aiIconDragging.value) return;
  const icon = aiIconRef.value;
  if (!icon) return;
  const iconW = icon.offsetWidth;
  const iconH = icon.offsetHeight;
  const winW = window.innerWidth;
  const winH = window.innerHeight;
  let left = e.clientX - aiIconOffset.value.x;
  let top = e.clientY - aiIconOffset.value.y;
  // 限制在窗口内
  left = Math.max(0, Math.min(left, winW - iconW));
  top = Math.max(0, Math.min(top, winH - iconH));
  aiIconPos.value.left = left;
  aiIconPos.value.top = top;
};
const onAiIconMouseUp = () => {
  aiIconDragging.value = false;
  document.body.style.overflow = '';
  document.removeEventListener('mousemove', onAiIconMouseMove);
  document.removeEventListener('mouseup', onAiIconMouseUp);
};
// 触摸事件
const onAiIconTouchStart = (e: TouchEvent) => {
  aiIconDragging.value = true;
  const icon = aiIconRef.value;
  if (icon && e.touches.length > 0) {
    const rect = icon.getBoundingClientRect();
    aiIconOffset.value = {
      x: e.touches[0].clientX - rect.left,
      y: e.touches[0].clientY - rect.top
    };
  }
  document.body.style.overflow = 'hidden'; // 禁止页面滚动
  document.addEventListener('touchmove', onAiIconTouchMove);
  document.addEventListener('touchend', onAiIconTouchEnd);
};
const onAiIconTouchMove = (e: TouchEvent) => {
  if (!aiIconDragging.value || e.touches.length === 0) return;
  const icon = aiIconRef.value;
  if (!icon) return;
  const iconW = icon.offsetWidth;
  const iconH = icon.offsetHeight;
  const winW = window.innerWidth;
  const winH = window.innerHeight;
  let left = e.touches[0].clientX - aiIconOffset.value.x;
  let top = e.touches[0].clientY - aiIconOffset.value.y;
  // 限制在窗口内
  left = Math.max(0, Math.min(left, winW - iconW));
  top = Math.max(0, Math.min(top, winH - iconH));
  aiIconPos.value.left = left;
  aiIconPos.value.top = top;
};
const onAiIconTouchEnd = () => {
  aiIconDragging.value = false;
  document.body.style.overflow = '';
  document.removeEventListener('touchmove', onAiIconTouchMove);
  document.removeEventListener('touchend', onAiIconTouchEnd);
};
onMounted(() => {
  // 初始位置（右下角）
  const icon = aiIconRef.value;
  if (icon) {
    const winW = window.innerWidth;
    const winH = window.innerHeight;
    const rect = icon.getBoundingClientRect();
    aiIconPos.value.left = winW - rect.width - 20;
    aiIconPos.value.top = winH - rect.height - 120;
  }
});

// 在onMounted中初始化
onMounted(() => {
  // 初始位置（右下角）
  const icon = aiIconRef.value;
  if (icon) {
    const winW = window.innerWidth;
    const winH = window.innerHeight;
    const rect = icon.getBoundingClientRect();
    aiIconPos.value.left = winW - rect.width - 20;
    aiIconPos.value.top = winH - rect.height - 120;
  }
});

// 在onMounted中初始化
onMounted(async () => {
  // 初始化用户和会员信息
  initUserAndMembership();

  // 等待视频数据加载完成
  await getData();

  isSearched.value = false;
  searchKey.value = "";

  if (route.query.tab !== undefined) {
    active.value = Number(route.query.tab);
  }

  if (route.query.search && typeof route.query.search === 'string') {
    searchKey.value = route.query.search;
  }

  // 添加storage事件监听
  window.addEventListener('storage', handleStorageChange);

  // 初始位置（右下角）
  const icon = aiIconRef.value;
  if (icon) {
    const winW = window.innerWidth;
    const winH = window.innerHeight;
    const rect = icon.getBoundingClientRect();
    aiIconPos.value.left = winW - rect.width - 20;
    aiIconPos.value.top = winH - rect.height - 120;
  }
});

onUnmounted(() => {
  // 移除storage事件监听
  window.removeEventListener('storage', handleStorageChange);
});

watch(active, () => {
  isSearched.value = false;
  searchKey.value = "";
});

watch(() => filteredData.value, () => {
  nextTick(() => {
    initLazyLoading();
  });
}, { immediate: true });

</script>

<template>
  <div class="video">
    <div class="sticky-header">
      <div class="search-bar">
        <el-input v-model="searchKey" @focus="goToSearchPage" @keyup.enter="goToSearchPage"
          :placeholder="getText('viaEyeMovement')" clearable class="search-input" />
      </div>

      <div class="tab-section">
        <h4>{{ getText('videoShareZone') }}</h4>
        <van-tabs v-model="currentType" @change="onTabChange" style="transition: all 0.3s ease;">
          <van-tab :title="getSportTypeText('all')" name="all" style="transition: all 0.3s ease;"></van-tab>
          <van-tab :title="getSportTypeText('running')" name="running" style="transition: all 0.3s ease;"></van-tab>
          <van-tab :title="getSportTypeText('cycling')" name="cycling" style="transition: all 0.3s ease;"></van-tab>
          <van-tab :title="getSportTypeText('yoga')" name="yoga" style="transition: all 0.3s ease;"></van-tab>
          <van-tab :title="getSportTypeText('fitness')" name="fitness" style="transition: all 0.3s ease;"></van-tab>
        </van-tabs>
      </div>
    </div>

    <div class="content-area">
      <div class="video-grid" style="transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);">
        <div v-for="item in filteredData" :key="item.id" class="video-card" @click="goToDetail(item)"
          style="transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);"
          onmouseover="this.style.transform='translateY(-8px) scale(1.02)'; this.style.boxShadow='0 20px 40px rgba(102, 126, 234, 0.25)';"
          onmouseout="this.style.transform='translateY(0) scale(1)'; this.style.boxShadow='0 8px 32px rgba(0, 0, 0, 0.12)';">
          <!-- 原有内容 -->
          <div class="card-image-wrapper">
            <img :src="item.img" :alt="item.name" class="card-image" @error="onImageError"
              style="transition: transform 0.3s ease;" onmouseover="this.style.transform='scale(1.08)';"
              onmouseout="this.style.transform='scale(1)';" />
            <div class="card-type-tag">{{ item.type }}</div>
            <div v-if="item.isMemberOnly" class="member-badge">
              <span class="member-icon">👑</span>
              <span class="member-text">会员专属</span>
            </div>
            <div v-if="item.isMemberOnly" class="member-lock-overlay">
              <div class="lock-content">
                <div class="lock-icon">🔒</div>
                <div class="lock-text">会员专属</div>
              </div>
            </div>
          </div>
          <div class="card-info">
            <h3 class="card-title">{{ item.name }}</h3>
            <div class="card-meta">
              <span class="card-time">{{ formatTime(item.time || '') }}</span>
              <span v-if="item.isMemberOnly" class="member-indicator">👑</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 固定的AI图标 -->
    <div class="ai-icon-fixed" ref="aiIconRef"
      :style="{ left: aiIconPos.left + 'px', top: aiIconPos.top + 'px', position: 'fixed', zIndex: 1000, cursor: aiIconDragging ? 'grabbing' : 'pointer' }"
      @mousedown="onAiIconMouseDown" @touchstart="onAiIconTouchStart" @click="handleAIClick">
      <van-icon name="chat-o" class="ai-icon" />
      <span class="ai-text">{{ getText('aiAssistant') }}</span>
    </div>

    <!-- AI聊天弹窗 -->
    <transition name="slide-up">
      <div v-if="showAIChat" class="ai-chat-overlay" @click="closeAIChat">
        <div class="ai-chat-container" @click.stop>
          <div class="ai-chat-header">
            <div class="ai-chat-title">
              <van-icon name="chat-o" class="ai-title-icon" />
              <span>{{ getText('aiFitnessAssistant') }}</span>
            </div>
            <div class="ai-chat-actions">
              <van-icon name="cross" class="ai-close-icon" @click="closeAIChat" />
            </div>
          </div>

          <div class="ai-chat-messages" ref="chatContainer">
            <div v-for="message in chatMessages" :key="message.id"
              :class="['message', message.isUser ? 'user-message' : 'ai-message']">
              <div class="message-content">
                {{ message.content }}
              </div>
              <div class="message-time">
                {{ message.timestamp.toLocaleTimeString(
                  currentLang === 'zh' ? 'zh-CN' :
                    currentLang === 'en' ? 'en-US' : 'ja-JP',
                  { hour: '2-digit', minute: '2-digit' }
                ) }}
              </div>
            </div>

            <!-- 加载状态 -->
            <div v-if="isLoading" class="message ai-message">
              <div class="message-content">
                <div class="loading-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>

          <div class="ai-chat-input">
            <el-input v-model="currentMessage" :placeholder="getText('enterYourQuestion')" @keyup.enter="sendMessage"
              :disabled="isLoading" class="chat-input" />
            <el-button type="primary" @click="sendMessage" :disabled="isLoading || !currentMessage.trim()"
              class="send-button">
              <van-icon name="send" />
            </el-button>
          </div>
        </div>
      </div>
    </transition>

    <!-- 会员解锁弹窗 -->
    <transition name="fade">
      <div v-if="showMembershipPopup" class="membership-popup-overlay" @click="closeMembershipPopup">
        <div class="membership-popup" @click.stop>
          <div class="popup-header">
            <div class="popup-title">
              <span class="crown-icon">👑</span>
              <span>会员专属内容</span>
            </div>
            <div class="popup-close" @click="closeMembershipPopup">✕</div>
          </div>

          <div class="popup-content">
            <div class="video-preview">
              <img :src="selectedVideo?.img" :alt="selectedVideo?.name" class="preview-image" />
              <div class="preview-overlay">
                <div class="lock-icon-large">🔒</div>
              </div>
            </div>

            <div class="video-info">
              <h3 class="video-title">{{ selectedVideo?.name }}</h3>
              <p class="video-type">{{ selectedVideo?.type }}</p>
            </div>



            <div class="membership-benefits">
              <h4>会员特权</h4>
              <ul class="benefits-list">
                <li>🎬 专属高质量视频内容</li>
                <li>📱 无广告观看体验</li>
                <li>💎 优先获得新功能</li>
                <li>🎁 专属优惠和礼品</li>
              </ul>
            </div>
          </div>

          <div class="popup-actions">
            <button class="upgrade-btn" @click="upgradeMembership">
              <span class="upgrade-icon">💎</span>
              <span>立即升级会员</span>
            </button>
            <button class="cancel-btn" @click="closeMembershipPopup">稍后再说</button>
          </div>
        </div>
      </div>
    </transition>

  </div>
</template>

<style scoped>
.video {
  padding: 0;
}

.sticky-header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: #dff3fa;
  padding: 24px 20px 20px 20px;
  box-shadow: 0 4px 20px rgba(223, 243, 250, 0.3);
  border-radius: 0 0 24px 24px;
}

.content-area {
  height: calc(100vh - var(--tabbar-height, 65px));
  overflow-y: auto;
  padding: 0;
  margin: 0;
  background: #f8fafc;
  padding-bottom: env(safe-area-inset-bottom);
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.video-card {
  background: white;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  position: relative;
}

.video-card:hover {
  transform: translateY(-8px) scale(1.02);
  box-shadow: 0 20px 40px rgba(102, 126, 234, 0.25);
}

.card-image-wrapper {
  position: relative;
  width: 100%;
  height: 180px;
  overflow: hidden;
  background: #dff3fa;
}

.card-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.video-card:hover .card-image {
  transform: scale(1.08);
}

.card-type-tag {
  position: absolute;
  top: 12px;
  right: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.card-info {
  padding: 16px 20px;
  background: white;
}

.card-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 700;
  color: #1a202c;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  letter-spacing: -0.025em;
}

.card-meta {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #7f8c8d;
  margin-bottom: 8px;
}

.card-time {
  color: #95a5a6;
}

.lazy-image {
  opacity: 0;
  transition: opacity 0.4s ease-in-out;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  filter: blur(8px);
}

.lazy-image.loaded {
  opacity: 1;
  filter: blur(0);
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  justify-content: center;
}

.tab-section {
  margin-bottom: 20px;
  text-align: center;
}

.tab-section h4 {
  color: #2c5282;
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 16px 0;
  text-shadow: 0 1px 2px rgba(44, 82, 130, 0.1);
}

.search-input {
  width: 100%;
  max-width: 400px;
}

:deep(.el-input__inner) {
  height: 44px;
  font-size: 16px;
  border-radius: 22px;
  border: none;
  background: transparent;
  backdrop-filter: none;
  box-shadow: none;
  transition: all 0.3s ease;
}

:deep(.el-input__inner):focus {
  background: transparent;
  box-shadow: none;
  transform: none;
}

@media (max-width: 700px) {
  .video-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }

  .card-image-wrapper {
    height: 140px;
  }

  .card-title {
    font-size: 14px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    -webkit-line-clamp: 2;
  }

  .card-info {
    padding: 12px 14px;
  }

  .card-meta {
    font-size: 11px;
  }

  .card-type-tag {
    font-size: 10px;
    padding: 4px 8px;
  }

  .sticky-header {
    padding: 16px 16px 12px 16px;
  }

  .content-area {
    padding: 16px;
  }

  .tab-section h4 {
    font-size: 20px;
  }

  .ai-icon-fixed {
    width: 50px;
    height: 50px;
  }

  .ai-icon {
    font-size: 20px;
  }

  .ai-text {
    font-size: 9px;
  }

  /* AI聊天弹窗移动端样式 */
  .ai-chat-container {
    width: 95%;
    height: 90%;
    border-radius: 15px;
  }

  .ai-chat-header {
    padding: 12px 16px;
    font-size: 16px;
  }

  .ai-title-icon {
    font-size: 20px;
  }

  .ai-close-icon {
    font-size: 20px;
  }

  .ai-chat-messages {
    padding: 15px;
  }

  .message {
    max-width: 85%;
    padding: 8px 12px;
  }

  .message-content {
    font-size: 13px;
  }

  .message-time {
    font-size: 9px;
  }

  .ai-chat-input {
    padding: 12px 16px;
  }

  .chat-input {
    height: 40px;
    font-size: 13px;
  }

  .send-button {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
}

/* AI图标样式 */
.ai-icon-fixed {
  position: fixed;
  bottom: 120px;
  right: 20px;
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 1000;
  border: 2px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

.ai-icon-fixed:hover {
  transform: translateY(-4px) scale(1.1);
  box-shadow: 0 12px 32px rgba(102, 126, 234, 0.6);
}

.ai-icon {
  font-size: 24px;
  color: white;
  margin-bottom: 2px;
}

.ai-text {
  font-size: 10px;
  color: white;
  font-weight: 600;
  text-align: center;
  line-height: 1;
}

/* AI聊天弹窗样式 */
.ai-chat-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  backdrop-filter: blur(10px);
}

.ai-chat-container {
  background: white;
  border-radius: 20px;
  width: 90%;
  max-width: 500px;
  height: 80%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.ai-chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 18px;
  font-weight: 700;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.ai-chat-title {
  display: flex;
  align-items: center;
}

.ai-title-icon {
  margin-right: 8px;
  font-size: 24px;
}

.ai-chat-actions {
  display: flex;
  gap: 10px;
}

.ai-close-icon {
  font-size: 24px;
  color: white;
  cursor: pointer;
}

.ai-chat-messages {
  flex-grow: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
  background: #f8f9fa;
}

.message {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 15px;
  position: relative;
}

.user-message {
  align-self: flex-end;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.ai-message {
  align-self: flex-start;
  background: #e9ecef;
  border: 1px solid rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.message-content {
  word-break: break-word;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.user-message .message-content {
  color: white;
}

.message-time {
  font-size: 10px;
  color: #95a5a6;
  margin-top: 5px;
  align-self: flex-end;
}

.loading-dots {
  display: flex;
  gap: 5px;
}

.loading-dots span {
  display: inline-block;
  width: 8px;
  height: 8px;
  background-color: #667eea;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

.loading-dots span:nth-child(3) {
  animation-delay: 0s;
}

@keyframes bounce {

  0%,
  80%,
  100% {
    transform: translateY(-10px);
    opacity: 0.6;
  }

  40% {
    transform: translateY(0);
    opacity: 1;
  }
}

.ai-chat-input {
  display: flex;
  padding: 15px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  border-radius: 0 0 20px 20px;
  gap: 10px;
}

.chat-input {
  flex-grow: 1;
  height: 44px;
  border-radius: 22px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 0 15px;
  font-size: 14px;
  color: #333;
  background: transparent;
  box-shadow: none;
}

.send-button {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: background 0.3s ease;
}

.send-button:hover {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
}

.send-button:active {
  transform: scale(0.95);
}

/* 过渡动画 */
.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}

.slide-up-enter-from {
  transform: translateY(100%);
  opacity: 0;
}

.slide-up-leave-to {
  transform: translateY(100%);
  opacity: 0;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 会员相关样式 */
.member-only {
  position: relative;
  opacity: 0.8;
}

.member-badge {
  position: absolute;
  top: 12px;
  left: 12px;
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
  color: #333;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 10px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 4px;
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3);
  z-index: 2;
}

.member-icon {
  font-size: 12px;
}

.member-text {
  font-size: 10px;
  white-space: nowrap;
}

.member-lock-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 3;
  backdrop-filter: blur(2px);
}

.lock-content {
  text-align: center;
  color: white;
}

.lock-icon {
  font-size: 32px;
  margin-bottom: 8px;
  display: block;
}

.lock-text {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 4px;
}

.lock-subtext {
  font-size: 12px;
  opacity: 0.8;
}

.member-indicator {
  margin-left: 8px;
  font-size: 14px;
}

/* 会员弹窗样式 */
.membership-popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
  backdrop-filter: blur(8px);
}

.membership-popup {
  background: white;
  border-radius: 20px;
  width: 90%;
  max-width: 400px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  animation: popupSlideIn 0.3s ease-out;
}

@keyframes popupSlideIn {
  from {
    transform: translateY(50px) scale(0.9);
    opacity: 0;
  }

  to {
    transform: translateY(0) scale(1);
    opacity: 1;
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.popup-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.crown-icon {
  font-size: 20px;
}

.popup-close {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
  color: #666;
  transition: all 0.2s;
}

.popup-close:hover {
  background: #e0e0e0;
  color: #333;
}

.popup-content {
  padding: 0 20px;
}

.video-preview {
  position: relative;
  width: 100%;
  height: 200px;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 20px;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.lock-icon-large {
  font-size: 48px;
  color: white;
}

.video-info {
  margin-bottom: 20px;
}

.video-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.video-type {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.membership-requirements {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
}

.requirement-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.requirement-icon {
  font-size: 16px;
}

.requirement-text {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.current-level-info {
  border-top: 1px solid #e9ecef;
  padding-top: 12px;
}

.current-level-text {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.level-progress {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: #e9ecef;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4CAF50, #66BB6A);
  border-radius: 3px;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 12px;
  color: #666;
  min-width: 30px;
}

.no-membership {
  text-align: center;
  padding: 20px 0;
}

.no-membership-text {
  font-size: 14px;
  color: #666;
}

.membership-benefits {
  margin-bottom: 20px;
}

.membership-benefits h4 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.benefits-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.benefits-list li {
  padding: 8px 0;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 8px;
}

.popup-actions {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.upgrade-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 16px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.upgrade-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.upgrade-icon {
  font-size: 18px;
}

.cancel-btn {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #e9ecef;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background: #e9ecef;
  color: #333;
}

/* 移动端适配 */
@media (max-width: 700px) {
  .membership-popup {
    width: 95%;
    max-height: 85vh;
  }

  .popup-header {
    padding: 16px 16px 0 16px;
  }

  .popup-content {
    padding: 0 16px;
  }

  .video-preview {
    height: 160px;
  }

  .lock-icon-large {
    font-size: 36px;
  }

  .popup-actions {
    padding: 16px;
  }

  .upgrade-btn {
    padding: 14px;
    font-size: 15px;
  }

  .member-badge {
    font-size: 9px;
    padding: 3px 6px;
  }

  .member-text {
    font-size: 9px;
  }
}
</style>